<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitereview
 * @copyright  Copyright 2012-2013 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: install.php 6590 2013-04-01 00:00:00Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitereview_Installer extends Engine_Package_Installer_Module {

  function onPreinstall() {
    $db = $this->getDb();
    $PRODUCT_TYPE = 'sitereview';
    $PLUGIN_TITLE = 'Sitereview';
    $PLUGIN_VERSION = '4.5.0';
    $PLUGIN_CATEGORY = 'plugin';
    $PRODUCT_DESCRIPTION = 'Reviews & Ratings';
    $_PRODUCT_FINAL_FILE = 0;
    $SocialEngineAddOns_version = '4.5.0p1';
    $PRODUCT_TITLE = 'Reviews & Ratings';
    $file_path = APPLICATION_PATH . "/application/modules/$PLUGIN_TITLE/controllers/license/ilicense.php";
    $is_file = file_exists($file_path);

    if (empty($is_file)) {
      include_once APPLICATION_PATH . "/application/modules/$PLUGIN_TITLE/controllers/license/license3.php";
    } else {
      $select = new Zend_Db_Select($db);
      $select->from('engine4_core_modules')->where('name = ?', $PRODUCT_TYPE);
      $is_Mod = $select->query()->fetchObject();
      if (empty($is_Mod)) {
        include_once $file_path;
      }
    }
    parent::onPreinstall();
  }

  function onInstall() {
  
    $db = $this->getDb();
    
    //ADD email_notify COLUMN IN EDITOR TABLE
    $email_notifiy = $db->query("SHOW COLUMNS FROM engine4_sitereview_editors LIKE 'email_notify'")->fetch();
    if(empty($email_notifiy)) {
      $db->query("ALTER TABLE `engine4_sitereview_editors` ADD `email_notify` TINYINT( 1 ) NOT NULL DEFAULT '1'");
    }
    
    //CODE FOR INCREASE THE SIZE OF engine4_activity_notifications's FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_activity_actionsettings LIKE 'type'")->fetch();
    if (!empty($type_array)) { 
      $varchar = $type_array['Type']; 
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 64) {
        $run_query = $db->query("ALTER TABLE `engine4_activity_actionsettings` CHANGE `type` `type` VARCHAR( 64 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }
    
    //CODE FOR INCREASE THE SIZE OF engine4_activity_notifications's FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_activity_actiontypes LIKE 'type'")->fetch();
    if (!empty($type_array)) { 
      $varchar = $type_array['Type']; 
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 64) {
        $run_query = $db->query("ALTER TABLE `engine4_activity_actiontypes` CHANGE `type` `type` VARCHAR( 64 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }
    
    $db = $this->getDb();

    $db->query("UPDATE  `engine4_seaocores` SET  `is_activate` =  '1' WHERE  `engine4_seaocores`.`module_name` ='sitereview';");

    $otherInfoTable = $db->query('SHOW TABLES LIKE \'engine4_sitereview_otherinfo\'')->fetch();
    if (!empty($otherInfoTable)) {
      $db->query("ALTER TABLE `engine4_sitereview_otherinfo` CHANGE `overview` `overview` LONGTEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL");
      $db->query("ALTER TABLE `engine4_sitereview_otherinfo` CHANGE `phone` `phone` VARCHAR( 32 ) NULL DEFAULT NULL");
      $db->query("ALTER TABLE `engine4_sitereview_otherinfo` CHANGE `email` `email` VARCHAR( 128 ) NULL DEFAULT NULL");
      $db->query("ALTER TABLE `engine4_sitereview_otherinfo` CHANGE `website` `website` VARCHAR( 255 ) NULL DEFAULT NULL");
    }

    $select = new Zend_Db_Select($db);
    $select
            ->from('engine4_core_modules')
            ->where('name = ?', 'sitereview')
            ->where('version < ?', '4.3.0p3');
    $is_enabled = $select->query()->fetchObject();

    if ($is_enabled) {
      $listingTypes = $db->select()
              ->from('engine4_sitereview_listingtypes', 'listingtype_id')
              ->query()
              ->fetchAll();
      foreach ($listingTypes as $listingType) {
        $listingTypeId = $listingType['listingtype_id'];

        $params = $db->select()
                ->from('engine4_core_menuitems', 'params')
                ->where("name = ?", "core_main_sitereview_listtype_$listingTypeId")
                ->limit(1)
                ->query()
                ->fetchColumn();

        if (!empty($params)) {
          $params = Zend_Json::decode($params);
          $params['route'] = "sitereview_general_listtype_".$listingTypeId;
          $params['listingtype_id'] = $listingTypeId;
          $params = Zend_Json::encode($params);

          $db->query("UPDATE `engine4_core_menuitems` SET `plugin` = 'Sitereview_Plugin_Menus::canViewSitereviews', `params` = '$params' WHERE `name` Like 'core_main_sitereview_listtype_$listingTypeId'");
        }

        $paramsMobile = $db->select()
                ->from('engine4_core_menuitems', 'params')
                ->where("name = ?", "mobi_browse_sitereview_listtype_$listingTypeId")
                ->limit(1)
                ->query()
                ->fetchColumn();

        if (!empty($paramsMobile)) {
          $paramsMobile = Zend_Json::decode($paramsMobile);
          $paramsMobile['route'] = "sitereview_general_listtype_".$listingTypeId;
          $paramsMobile['listingtype_id'] = $listingTypeId;
          $paramsMobile = Zend_Json::encode($paramsMobile);

          $db->query("UPDATE `engine4_core_menuitems` SET `plugin` = 'Sitereview_Plugin_Menus::canViewSitereviews', `params` = '$paramsMobile' WHERE `name` Like 'mobi_browse_sitereview_listtype_$listingTypeId'");
        }
      }
    }

    //IF 'engine4_seaocore_follows' TABLE IS NOT EXIST THAN CREATE'
    $seocoreFollowTable = $db->query('SHOW TABLES LIKE \'engine4_seaocore_follows\'')->fetch();
    if (empty($seocoreFollowTable)) {
      $db->query("CREATE TABLE IF NOT EXISTS `engine4_seaocore_follows` (
        `follow_id` int(11) unsigned NOT NULL auto_increment,
        `resource_type` varchar(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
        `resource_id` int(11) unsigned NOT NULL,
        `poster_type` varchar(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
        `poster_id` int(11) unsigned NOT NULL,
        `creation_date` datetime NOT NULL,
        PRIMARY KEY  (`follow_id`),
        KEY `resource_type` (`resource_type`, `resource_id`),
        KEY `poster_type` (`poster_type`, `poster_id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci ;");

      $select = new Zend_Db_Select($db);
      $advancedactivity = $select->from('engine4_core_modules', 'name')
              ->where('name = ?', 'advancedactivity')
              ->query()
              ->fetchcolumn();

      $is_enabled = $select->query()->fetchObject();
      if (!empty($advancedactivity)) {
        $db->query('INSERT IGNORE INTO `engine4_activity_actiontypes` (`type`, `module`, `body`, `enabled`, `displayable`, `attachable`, `commentable`, `shareable`, `is_generated`, `is_grouped`) VALUES ("follow_sitereview_wishlist", "sitereview", \'{item:$subject} is following {item:$owner}\'\'s {item:$object:wishlist}: {body:$body}\', 1, 5, 1, 1, 1, 1, 1)');
      } else {
        $db->query('INSERT IGNORE INTO `engine4_activity_actiontypes` (`type`, `module`, `body`, `enabled`, `displayable`, `attachable`, `commentable`, `shareable`, `is_generated`) VALUES ("follow_sitereview_wishlist", "sitereview", \'{item:$subject} is following {item:$owner}\'\'s {item:$object:wishlist}: {body:$body}\', 1, 1, 1, 1, 1, 1)');
      }
    }

    //CODE FOR INCREASE THE SIZE OF engine4_activity_actions FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_activity_actions LIKE 'type'")->fetch();
    if (!empty($type_array)) {
      $varchar = $type_array['Type'];
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 64) {
        $run_query = $db->query("ALTER TABLE `engine4_activity_actions` CHANGE `type` `type` VARCHAR( 64 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }

    //CODE FOR INCREASE THE SIZE OF engine4_activity_stream FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_activity_stream LIKE 'type'")->fetch();
    if (!empty($type_array)) {
      $varchar = $type_array['Type'];
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 64) {
        $run_query = $db->query("ALTER TABLE `engine4_activity_stream` CHANGE `type` `type` VARCHAR( 64 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }

    //CODE FOR INCREASE THE SIZE OF engine4_authorization_permissions's FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_authorization_permissions LIKE 'type'")->fetch();
    if (!empty($type_array)) {
      $varchar = $type_array['Type'];
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 32) {
        $run_query = $db->query("ALTER TABLE `engine4_authorization_permissions` CHANGE `type` `type` VARCHAR( 32 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }

    //CODE FOR INCREASE THE SIZE OF engine4_authorization_permissions's FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_authorization_permissions LIKE 'name'")->fetch();
    if (!empty($type_array)) {
      $varchar = $type_array['Type'];
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 32) {
        $run_query = $db->query("ALTER TABLE `engine4_authorization_permissions` CHANGE `name` `name` VARCHAR( 32 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }

    //CODE FOR INCREASE THE SIZE OF engine4_authorization_allow's FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_authorization_allow LIKE 'resource_type'")->fetch();
    if (!empty($type_array)) {
      $varchar = $type_array['Type'];
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 32) {
        $run_query = $db->query("ALTER TABLE `engine4_authorization_allow` CHANGE `resource_type` `resource_type` VARCHAR( 32 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }

    //CHANGE IN CORE COMMENT TABLE
    $table_exist = $db->query("SHOW TABLES LIKE 'engine4_core_comments'")->fetch();
    if (!empty($table_exist)) {
      $column_exist = $db->query("SHOW COLUMNS FROM `engine4_core_comments` LIKE 'parent_comment_id'")->fetch();
      if (empty($column_exist)) {
        $db->query("ALTER TABLE  `engine4_core_comments` ADD  `parent_comment_id` INT( 11 ) NOT NULL DEFAULT  '0';");
      }
    }

    //CODE FOR INCREASE THE SIZE OF engine4_authorization_allow's FIELD type
    $type_array = $db->query("SHOW COLUMNS FROM engine4_authorization_allow LIKE 'action'")->fetch();
    if (!empty($type_array)) {
      $varchar = $type_array['Type'];
      $length_varchar = explode("(", $varchar);
      $length = explode(")", $length_varchar[1]);
      $length_type = $length[0];
      if ($length_type < 32) {
        $run_query = $db->query("ALTER TABLE `engine4_authorization_allow` CHANGE `action` `action` VARCHAR( 32 ) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL");
      }
    }

    $this->_checkFfmpegPath();
    parent::onInstall();
  }

  protected function _checkFfmpegPath() {

    $db = $this->getDb();
    $select = new Zend_Db_Select($db);

    //CHECK FFMPEG PATH FOR CORRECTNESS
    if (function_exists('exec') && function_exists('shell_exec')) {

      //API IS NOT AVAILABLE
      //$ffmpeg_path = Engine_Api::_()->getApi('settings', 'core')->video_ffmpeg_path;
      $ffmpeg_path = $db->select()
              ->from('engine4_core_settings', 'value')
              ->where('name = ?', 'sitereview_video.ffmpeg.path')
              ->limit(1)
              ->query()
              ->fetchColumn(0);

      $output = null;
      $return = null;
      if (!empty($ffmpeg_path)) {
        exec($ffmpeg_path . ' -version', $output, $return);
      }

      //TRY TO AUTO-GUESS FFMPEG PATH IF IT IS NOT SET CORRECTLY
      $ffmpeg_path_original = $ffmpeg_path;
      if (empty($ffmpeg_path) || $return > 0 || stripos(join('', $output), 'ffmpeg') === false) {
        $ffmpeg_path = null;

        //WINDOWS
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
          // @todo
        }
        //NOT WINDOWS
        else {
          $output = null;
          $return = null;
          @exec('which ffmpeg', $output, $return);
          if (0 == $return) {
            $ffmpeg_path = array_shift($output);
            $output = null;
            $return = null;
            exec($ffmpeg_path . ' -version', $output, $return);
            if (0 == $return) {
              $ffmpeg_path = null;
            }
          }
        }
      }
      if ($ffmpeg_path != $ffmpeg_path_original) {
        $count = $db->update('engine4_core_settings', array(
            'value' => $ffmpeg_path,
                ), array(
            'name = ?' => 'sitereview.video.ffmpeg.path',
        ));
        if ($count === 0) {
          try {
            $db->insert('engine4_core_settings', array(
                'value' => $ffmpeg_path,
                'name' => 'sitereview.video.ffmpeg.path',
            ));
          } catch (Exception $e) {
            
          }
        }
      }
    }
  }

  function onDisable() {

    $db = $this->getDb();

    $select = new Zend_Db_Select($db);
    $isSitereviewEnabled = $select
            ->from('engine4_core_modules', 'enabled')
            ->where('name = ?', 'sitereviewlistingtype')
            ->where('enabled = ?', 1)
            ->query()
            ->fetchColumn()
    ;

    if ($isSitereviewEnabled) {
      $base_url = Zend_Controller_Front::getInstance()->getBaseUrl();
      $error_msg1 = Zend_Registry::get('Zend_Translate')->_('Note: Please disable "Reviews & Ratings - Multiple Listing Types Extension" before disabling the "Reviews & Ratings Plugin" itself.');
      echo "<div style='background-color: #E9F4FA;border-radius:7px 7px 7px 7px;float:left;overflow: hidden;padding:10px;'><div style='background:#FFFFFF;border:1px solid #D7E8F1;overflow:hidden;padding:20px;'><span style='color:red'>$error_msg1</span> <a href='" . $base_url . "/manage'>Click here</a> to go Manage Packages.</div></div>";
      die;
    }

    parent::onDisable();
  }

}
